package com.yyplatform.admin.platform.schedule.quartz;

import java.lang.reflect.Method;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.yyplatform.admin.platform.schedule.model.entity.JobEntity;
import com.yyplatform.admin.platform.schedule.model.entity.JobLogEntity;
import com.yyplatform.admin.platform.schedule.service.JobLogService;
import com.yyplatform.admin.platform.schedule.service.JobService;
import com.yyplatform.admin.infra.exception.ErrorCode;
import com.yyplatform.admin.infra.utils.SpringContextUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * Created on 2024-11-15
 */
@Slf4j
public class QuartzProxyJob extends QuartzJobBean {
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        JobEntity jobEntity = (JobEntity) context.getMergedJobDataMap().
                get(JobService.JOB_PARAM_KEY);

        log.info("jobEntity info=[{}]", jobEntity.getBeanName());

        //数据库保存执行记录
        JobLogEntity logEntity = new JobLogEntity();
        logEntity.setJobId(jobEntity.getId());
        logEntity.setBeanName(jobEntity.getBeanName());
        logEntity.setParams(jobEntity.getParams());
        logEntity.setErrorCode(ErrorCode.SUCCESS.getCode());
        logEntity.setErrorMsg("OK");


        //任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            //执行任务
            log.info("任务准备执行，任务ID：{}", jobEntity.getId());
            Object target = SpringContextUtils.getBeanByName(jobEntity.getBeanName());
            Method method = target.getClass().getDeclaredMethod("run", String.class);
            method.invoke(target, jobEntity.getParams());

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            logEntity.setCost((int) times);
            //任务状态
            logEntity.setErrorCode(ErrorCode.SUCCESS.getCode());

            log.info("任务执行完毕，任务ID：{}  总共耗时：{} 毫秒", jobEntity.getId(), times);
        } catch (Exception e) {
            log.error("任务执行失败，任务ID：{}", jobEntity.getId(), e);

            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            logEntity.setCost((int) times);

            //任务状态
            logEntity.setErrorCode(ErrorCode.UNKNOW_ERROR.getCode());
            logEntity.setErrorMsg(ExceptionUtils.getStackTrace(e));
        } finally {
            //获取spring bean
            JobLogService scheduleJobLogService = SpringContextUtils.getBeanByClass(JobLogService.class);
            scheduleJobLogService.save(logEntity);
        }
    }
}
